import logging
import re
from typing import Dict, Any

import requests
from bs4 import BeautifulSoup

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("jsl_bond_detail")


class JslDetailConfig:

    def __init__(self):
        self.cb_detail_base_url = "https://www.jisilu.cn/data/cbnew/detail/"
        self.cookie=""


# -------------------------- 5. 数据处理（核心：中文列名替换） --------------------------

class BondDetailMapper:
    #  处理respomse   获取
    def get_cb_rates_dic_jsl(self, text: str) -> Dict[str, Any]:

        soup = BeautifulSoup(text, "html.parser")

        # # 1. 找到 grid_cb_content
        grid_cb_content = soup.find("div", class_="grid cb_content")

        # # 2. 找到所有 class 包含 'grid-row' 的 div
        grid_rows = grid_cb_content.find_all("div", class_="grid-row")
        third_row = grid_rows[2]
        long_text_tags = third_row.find_all("td", class_="long_text")
        text_align_center_tags = third_row.find_all("td", class_="vertical_align_middle text_align_center")

        next_td_content = None
        # 筛选到到期赎回价
        for tag in text_align_center_tags:
            text = tag.get_text()  # 去掉前后空白
            if "赎回价" in text:
                # 获取下一个td元素
                next_td = tag.find_next_sibling("td")
                if next_td:
                    next_td_content = next_td.get_text(strip=True)
                break  # 找到后退出循环



        # 遍历查找包含“第一年”的标签
        for tag in long_text_tags:
            text = tag.get_text(strip=True)  # 去掉前后空白
            if "第一年" in text or "第1年" in text or "一年" in text:
                rates_text = text
                break

        rate_dict = {}
        pattern = r'(\d+\.\d+|\d+)'  # 匹配整数或小数的正则表达式
        i = 1
        pairs = re.split(r"[、,，]", rates_text)
        print(pairs)
        for pair in pairs:
            # 提取年份数字（如从“第一年”中提取“1”并转为int）
            match = re.search(pattern, pair)
            rate = float(match.group(0))  # 筛选字符串中的第一个数字
            # 将年份数字作为键，利率作为值存入字典
            rate_dict[i] = rate
            i += 1
        print(next_td_content, rate_dict)
        return next_td_content, rate_dict


# -------------------------- 6. 数据获取（复用你已有的逻辑） --------------------------


class BondDetail:
    def __init__(self):
        # 创建会话对象，复用连接
        self.session = requests.Session()
        self.bond_detail_mapper = BondDetailMapper()
        self.jsl_detail_config = JslDetailConfig()

    def get_bond_detail(self, bond_id: str) -> None:
        try:
            # 构造请求头（与Java代码中的setHeader一一对应）
            headers = {
                "Accept": "application/json, text/plain, */*",
                "Accept-Encoding": "gzip, deflate, br, zstd",
                "Accept-Language": "en,en-GB;q=0.9,en-US;q=0.8,zh-CN;q=0.7,zh;q=0.6",
                "Columns": "1,70,2,3,5,6,11,12,14,15,16,29,30,32,34,44,46,47,50,52,53,54,56,57,58,59,60,62,63,67",
                "Cookie": self.jsl_detail_config.cookie,
                "If-Modified-Since": "Tue, 14 Jan 2025 08:03:36 GMT",
                "Init": "1",
                "Priority": "u=1, i",
                "Referer": "",
                "Sec-Ch-Ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
                "Sec-Ch-Ua-Mobile": "?0",
                "Sec-Ch-Ua-Platform": "\"Windows\"",
                "Sec-Fetch-Dest": "empty",
                "Sec-Fetch-Mode": "cors",
                "Sec-Fetch-Site": "same-origin",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
            }

            # 发送GET请求（对应Java的HttpGet）
            response = self.session.get(
                url=self.jsl_detail_config.cb_detail_base_url+bond_id,
                headers=headers,
                timeout=10  # 设置超时时间
            )
            # 检查响应状态码（对应Java的statusCode != 200判断）
            if response.status_code != 200:
                logger.error(f"集思录请求转债明细失败，状态码: {response.status_code}")
                # TODO: 实现发送邮件通知的逻辑
                return
            text = response.text
            return text
        except requests.exceptions.RequestException as e:
            logger.error(f"HTTP请求异常: {str(e)}")


# 示例调用
if __name__ == "__main__":
    # 实际使用时替换为真实的URL和Cookie
    fetcher = BondDetail()
    respose_txt = fetcher.get_bond_detail(
        "113033"

    )
    aaa,dic =fetcher.bond_detail_mapper.get_cb_rates_dic_jsl(respose_txt)
    print(dic)
